package com.yishan.gulimall.springsecurity.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yishan.gulimall.springsecurity.config.R;
import com.yishan.gulimall.springsecurity.domain.LoginUser;
import com.yishan.gulimall.springsecurity.domain.User;
import com.yishan.gulimall.springsecurity.mapper.UserMapper;
import com.yishan.gulimall.springsecurity.service.LoginService;
import com.yishan.gulimall.springsecurity.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public R login(User user) {
        //这个地方传的值在userDetailsService中验证.
        //流程是authenticationManager-->providerManager-->userDetailsService(我们自定义的)->providerManager-->authenticationManager.
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(),null);
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        //获取userDetailService中返回的userDetails对象,进行强制转换.获取我们的用户信息.
        LoginUser principal = (LoginUser) authenticate.getPrincipal();
        User principalUser = principal.getUser();
        principalUser.setPermissions(principal.getPermissions());
        //设置权限
        //生成token
        String jwt = JwtUtils.createJWT(principalUser.getId().toString(), 1800);
        //存入redis
        stringRedisTemplate.opsForValue().set("token:"+jwt, JSON.toJSONString(principalUser),30, TimeUnit.MINUTES);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", jwt);
        jsonObject.put("user", user);
        return R.success(jsonObject);
    }

    @Override
    public R logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Boolean delete = stringRedisTemplate.delete("token:" + token);
        return R.success(null);
    }


}
